//
//  PersonInfoVController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/8.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "PersonInfoVController.h"
#import "PersonOneCell.h"
#import "PersonTwoCell.h"
#import "FixPassWordController.h"
#import "XiuGaiMiMaViewController.h"
#import "YanZhengPhoneVController.h"

@interface PersonInfoVController ()<UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate>



@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSArray *titA;
@property (nonatomic, strong)UIImage *tempImage;



@end

@implementation PersonInfoVController


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _tempImage = [UIImage imageNamed:@"shouye_xianshimiaosha"];
    _titA = @[@[@"头像",@"昵称"],@[@"修改密码",@"支付密码"]];
    [self configureNaBar];
    [self configureViewC];
}
- (void)configureNaBar {
    self.navigationItem.title = @"个人资料";
    //设置导航栏按钮的边距
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(handleBackAxtion) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    
    
    
}
- (void)handleBackAxtion {
    [self.navigationController popViewControllerAnimated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//配置视图控制器
- (void)configureViewC {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = kSpNone;
    _tableView.backgroundColor = KShouYeBg;
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"PersonOneCell" bundle:nil] forCellReuseIdentifier:@"PersonOneCell"];
     [self.tableView registerNib:[UINib nibWithNibName:@"PersonTwoCell" bundle:nil] forCellReuseIdentifier:@"PersonTwoCell"];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  
        return 2;

    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 90;
        }
        else {
            return 60;
        }
    }
    else {
        return 60;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else {
    return 10;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *bgV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 10)];
    bgV.backgroundColor = KShouYeBg;
    return bgV;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            PersonOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonOneCell"];
            cell.selectionStyle = kSeNone;
            [cell.photoImageV sd_setImageWithURL:[NSURL URLWithString:_pohotUrlStr]placeholderImage:[UIImage imageNamed:@"quetu"]];
            return cell;
        }else {
            PersonTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonTwoCell"];
            cell.nameTF.hidden = NO;
            cell.titleLB.text = _titA[0][1];
            cell.selectionStyle = kSeNone;
            cell.nameTF.text = _nameStr;
            [cell.nameTF addTarget:self action:@selector(textValueChanged:) forControlEvents:UIControlEventEditingDidEnd];
            
            return cell;
        }
    }else {
        PersonTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PersonTwoCell"];
        cell.selectionStyle = kSeNone;
        cell.titleLB.text = _titA[1][indexPath.row];
        if (indexPath.row == 0) {
            
            cell.jiantouV.hidden = NO;
        
        }
        if (indexPath.row == 1) {
            cell.jiantouV.hidden = NO;
            cell.liJiSheZhiLB.hidden = NO;
        }
        return cell;
    }
 
}


#pragma mark  －＝－＝－＝－＝－＝－＝ 修改个人昵称
- (void)textValueChanged:(UITextField *)text {
    
    if (text.text.length == 0) {
        [MBProgressHUD showText:@"请输入昵称哦"];
        return;
    }
    _nameStr = text.text;
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"nickname":_nameStr,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest postWithURLString:POST(Shop_PersonalModifyNickname) parameters:parameDic success:^(id responseObject) {
        
    } failure:^(NSError *error) {
    
    }];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
               [self updataPhotoimage];//更新头像;
        }
    }
    
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            YanZhengPhoneVController *yan = [[YanZhengPhoneVController alloc] init];
            yan.pushTypeStr = @"修改密码";
            [self.navigationController pushViewController:yan animated:YES];
        }
        if (indexPath.row == 1) {
            FixPassWordController *fix = [[FixPassWordController alloc] init];
            [self.navigationController pushViewController:fix animated:YES];
        }
    }
    
}
#pragma mark  －－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－更换头像
- (void)updataPhotoimage {
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照", @"从相册选择", nil];
    }
    else {
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
    }
    sheet.tag = 255;
    [sheet showInView:self.view];
    
}
#pragma mark - action sheet delegte
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    return;
                case 1: //相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 2: //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
            }
        }
        else {
            if (buttonIndex == 0) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}
#pragma mark －－ image picker delegte上传封面的相机代理事件－－》选择结束
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    UIImage*image = info[UIImagePickerControllerEditedImage];
    NSLog(@"-----------------%@",image);
    _tempImage  = image;
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    

    
    
    //压缩图片
    NSData *fileData = UIImageJPEGRepresentation(image, 0.0);
    NSString *encodedString = [fileData base64Encoding];
    [self postImage:encodedString :fileData];
    
    
    
}

- (void)postImage:(NSString *)encodedString :(NSData *)fileData {
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    NSDictionary *dic = @{@"file":fileData,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];
    Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/plain",@"text/html", nil];

    [Manager POST:POST(FileURL) parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:fileData name:@"file" fileName:@"file.png" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MBProgressHUD showText:@"更换头像出错"];
            
            return ;
        }
        if (![[NSString stringWithFormat:@"%@",responseObject[@"data"][@"code"]] isEqualToString:@"0"]) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MBProgressHUD showText:responseObject[@"data"][@"msg"]];
            return;
        }
        _pohotUrlStr =responseObject[@"data"][@"info"][@"url"];

        NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"headimgurl":responseObject[@"data"][@"info"][@"url"],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
        
        [HttpRequest postWithURLString:POST(Shop_PersonalModifyHeadimgurl) parameters:parameDic success:^(id responseObject) {
             [MBProgressHUD hideHUDForView:self.view animated:YES];
            if ([responseObject[@"ret"] intValue] != 200) {
               
                [MBProgressHUD showText:@"更换头像失败"];
                return ;
            }
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
            [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    [MBProgressHUD showText:@"更换头像成功"];
            
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MBProgressHUD showText:@"更换头像失败"];
        }];
        
        
        NSLog(@"返回的图片地址%@",responseObject);
     
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self.view showTextNoActivity:@"服务器异常" timeLength:1];
    }];
    
    

}

//取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}


@end
